import React, { useEffect, useReducer } from 'react'
import { useSelector } from 'react-redux'
import { httpgetPostList } from '../apis'
import HomeInput from '../components/Home/HomeInput'
import PostList from '../components/Home/PostList'
import UserCard from '../components/Home/UserCard'
import "./Home.scss"


const initialState = {
  list: [],
  totNum: 0,
}

function reducer(state,action) {
  let list;
  switch (action.type) {
    case "initList":
      list = action.list;
      return {
        ...state,
        list
      };
    case "addList":
      return {
        ...state,
        list:state.list.concat(action.list)
      };
    case "clearList":
      return {
        ...state,
        list: []
      }
    case "updateList":
      list = [...state.list];
      list[action.index] = action.post;
      return {
        ...state,
        list
      };
    case "setTotNum":
      const totNum = action.totNum;
      return {
        ...state,
        totNum
      }
    case "addPost":
      list = [...state.list];
      list.unshift(action.post);
      if(list.length>10) {
        list.pop();
      }
      return {
        ...state,
        list
      }
    default:
      return state;
  }
}


export default function Home() {
  const [state,dispatch] = useReducer(reducer,initialState);
  const user = useSelector(state => state.user);
  return (
    <div className='Home-container'>
      <div className='left-container'>
        <HomeInput state={state} dispatch={dispatch}></HomeInput>
        <PostList state={state} dispatch={dispatch}></PostList>
      </div>
      <div className='right-container'>
        {/* todo */}
        {
          user.userId && <UserCard state={state}></UserCard>
        }
      </div>
    </div>
  )
}
